package com.tan.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tan.common.domain.user.SysUserRole;
import com.tan.common.mapper.user.SysUserRoleMapper;
import com.tan.core.utils.ExceptionTool;
import com.tan.user.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户和角色关联表 服务实现类
 * </p>
 *
 * @author Tan
 * @since 2025-01-27
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Override
    public List<SysUserRole> byUser(Long userId) {
        return this.baseMapper.selectList(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getUserId, userId));
    }

    @Override
    public List<SysUserRole> byRole(Long roleId) {
        return this.baseMapper.selectList(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getRoleId, roleId));
    }

    @Override
    public List<SysUserRole> byRole(List<Long> ids) {
        if (ExceptionTool.isEmpty(ids)) return Collections.emptyList();
        return this.baseMapper.selectList(Wrappers.lambdaQuery(SysUserRole.class).in(SysUserRole::getRoleId, ids));
    }


    @Override
    public List<Long> rolesByUser(Long userId) {
        return this.byUser(userId).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
    }

    @Override
    public List<Long> usersByRole(Long roleId) {
        return this.byRole(roleId).stream().map(SysUserRole::getUserId).collect(Collectors.toList());
    }

    @Override
    public Set<Long> usersByRole(List<Long> roleIds) {
        return this.byRole(roleIds).stream().map(SysUserRole::getUserId).collect(Collectors.toSet());
    }
}
